<template>
  <div class="floating-input-container">
    <div class="input-wrapper">
      <el-input
          v-model="query"
          :placeholder="getPlaceholder()"
          class="floating-input-field"
          @keyup.enter="handleSubmit"
          :disabled="isLoading"
          size="large"
      />
      <el-button
          type="primary"
          class="floating-submit-btn"
          @click="handleSubmit"
          :loading="isLoading"
          size="large"
      >
        {{ isLoading ? '推荐中...' : '发送' }}
      </el-button>
    </div>
    
    <!-- 浮动操作按钮 -->
    <div class="floating-actions" v-if="currentUsername">
      <el-button
          type="text"
          class="floating-action-btn"
          @click="handleClearHistory"
          :disabled="!hasHistory || isLoading"
          size="small"
      >
        🗑️ 清空历史
      </el-button>
      <el-button
          type="text"
          class="floating-action-btn"
          @click="handleSwitchUser"
          :disabled="isLoading"
          size="small"
      >
        🔄 切换用户
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { getOutfitRecommendation, clearChatHistory } from '../api/outfitApi'
import eventBus from '../utils/eventBus'

// 响应式数据
const query = ref('')
const isLoading = ref(false)
const hasHistory = ref(false)
const currentUsername = ref('')
const isFirstMessage = ref(true)

// 接收父组件传递的props
const props = defineProps({
  historyCount: {
    type: Number,
    default: 0
  }
})

// 监听历史数量变化
watch(
    () => props.historyCount,
    (newVal) => {
      hasHistory.value = newVal > 0
    },
    { immediate: true }
)

// 计算属性：当前是否在用户对话模式
const isInUserMode = computed(() => currentUsername.value && !isFirstMessage.value)

// 获取动态占位符
const getPlaceholder = () => {
  if (isFirstMessage.value) {
    return "请输入您的穿搭需求，例如：我想了解职场穿搭、推荐运动装、帮我搭配约会服装等"
  } else if (currentUsername.value) {
    return `继续与${currentUsername.value}对话，或输入新的穿搭需求...`
  }
  return "请输入您的穿搭需求..."
}

// 智能识别用户名和意图
const analyzeInput = (input) => {
  const result = {
    username: '',
    intent: '',
    isUserIntroduction: false,
    isRecommendationRequest: false
  }
  
  // 1. 检查是否是用户介绍
  const introPatterns = [
    /^我是(.+)$/,
    /^我叫(.+)$/,
    /^我的名字是(.+)$/,
    /^我是(.+)，/,
    /^我叫(.+)，/
  ]
  
  for (const pattern of introPatterns) {
    const match = input.match(pattern)
    if (match) {
      result.username = match[1].trim()
      result.isUserIntroduction = true
      result.intent = 'user_introduction'
      return result
    }
  }
  
  // 2. 检查是否包含用户名（标准格式）
  const usernamePatterns = [
    /为(.+?)推荐/,
    /为(.+?)：/,
    /给(.+?)推荐/,
    /帮(.+?)搭配/,
    /(.+?)需要/,
    /(.+?)想要/
  ]
  
  for (const pattern of usernamePatterns) {
    const match = input.match(pattern)
    if (match) {
      result.username = match[1].trim()
      result.intent = 'recommendation_request'
      result.isRecommendationRequest = true
      return result
    }
  }
  
  // 3. 检查是否包含推荐关键词
  const recommendationKeywords = ['推荐', '穿搭', '搭配', '服装', '衣服', '穿什么', '怎么穿']
  const hasRecommendationKeyword = recommendationKeywords.some(keyword => input.includes(keyword))
  
  if (hasRecommendationKeyword) {
    result.intent = 'recommendation_request'
    result.isRecommendationRequest = true
  } else {
    result.intent = 'general_question'
  }
  
  return result
}

// 提交查询
const handleSubmit = async () => {
  const input = query.value.trim()
  if (!input) {
    ElMessage.warning('请输入内容')
    return
  }

  // 分析输入内容
  const analysis = analyzeInput(input)
  let username = currentUsername.value
  let processedQuery = input

  // 处理用户介绍
  if (analysis.isUserIntroduction) {
    username = analysis.username
    currentUsername.value = username
    isFirstMessage.value = false
    
    // 发送用户介绍事件
    eventBus.emit('user-introduced', { username, content: input })
    ElMessage.success(`欢迎 ${username}！现在可以进行自由对话了`)
    
    // 清空输入框，等待用户继续输入
    query.value = ''
    return
  }

  // 处理推荐请求
  if (analysis.isRecommendationRequest) {
    // 如果识别到用户名，更新当前用户
    if (analysis.username && analysis.username !== currentUsername.value) {
      username = analysis.username
      currentUsername.value = username
      isFirstMessage.value = false
      ElMessage.info(`已切换到用户：${username}`)
    }
    
    // 如果没有当前用户，提示先介绍自己
    if (!username) {
      ElMessage.warning('请先介绍自己，例如：我是小明，或者直接输入：为小明推荐职场穿搭')
      return
    }
    
    // 如果查询没有包含用户名，自动添加
    if (!input.includes(username)) {
      processedQuery = `为${username}：${input}`
    }
  } else {
    // 一般性问题，如果没有当前用户，提示先介绍自己
    if (!username) {
      ElMessage.warning('请先介绍自己，例如：我是小明，或者直接输入：为小明推荐职场穿搭')
      return
    }
    
    // 自动添加用户上下文
    processedQuery = `为${username}：${input}`
  }

  // 发送用户消息事件
  const timestamp = new Date().toLocaleString()
  
  // 添加调试日志
  console.log('🔍 发送用户消息事件:', { 
    content: input, 
    timestamp, 
    username: currentUsername.value 
  })
  
  eventBus.emit('add-user-message', { 
    content: input, 
    timestamp, 
    username: currentUsername.value 
  })
  eventBus.emit('user-query-submitted', { query: processedQuery, username })

  // 开始加载
  isLoading.value = true
  query.value = ''

  try {
    console.log('🚀 开始调用API:', processedQuery)
    
    await getOutfitRecommendation(
        processedQuery,
        (chunk) => {
          console.log('📨 收到AI消息片段:', chunk)
          eventBus.emit('add-ai-message-chunk', chunk)
        },
        (meta) => {
          console.log('✅ AI响应完成:', meta)
          isLoading.value = false
          eventBus.emit('ai-response-complete', meta)
          ElMessage.success('推荐完成！')
        },
        (errorMsg) => {
          console.log('❌ AI响应错误:', errorMsg)
          isLoading.value = false
          eventBus.emit('ai-response-error', errorMsg)
          ElMessage.error(errorMsg)
        }
    )
  } catch (error) {
    console.log('💥 API调用异常:', error)
    isLoading.value = false
    ElMessage.error('请求异常，请稍后重试')
  }
}

// 清空历史记录
const handleClearHistory = async () => {
  if (!currentUsername.value) {
    ElMessage.warning('请先进行一次推荐查询')
    return
  }

  try {
    await clearChatHistory(currentUsername.value)
    eventBus.emit('clear-history')
    ElMessage.success('历史记录已清空')
  } catch (error) {
    ElMessage.error(error.message)
  }
}

// 切换用户
const handleSwitchUser = () => {
  currentUsername.value = ''
  isFirstMessage.value = true
  query.value = ''
  eventBus.emit('user-switched')
  ElMessage.info('已切换到新用户模式，请输入您的穿搭需求')
}

// 监听用户切换事件
eventBus.on('force-switch-user', () => {
  handleSwitchUser()
})
</script>

<style scoped>
.floating-input-container {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  width: 90%;
  max-width: 800px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 1000;
  padding: 10px 20px;
  box-sizing: border-box;
}

.input-wrapper {
  display: flex;
  gap: 10px;
  width: 100%;
  max-width: 600px;
}

.floating-input-field {
  flex: 1;
  border-radius: 6px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s ease;
}

.floating-input-field:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px #409eff;
}

.floating-submit-btn {
  white-space: nowrap;
  border-radius: 6px;
  padding: 0 20px;
}

.floating-actions {
  display: flex;
  gap: 10px;
  margin-top: 10px;
  width: 100%;
  justify-content: center;
}

.floating-action-btn {
  color: #ff4d4f;
  font-size: 14px;
  padding: 5px 10px;
  border-radius: 6px;
  border: 1px solid #ff4d4f;
  transition: all 0.3s ease;
}

.floating-action-btn:hover {
  background-color: #ff4d4f;
  color: #fff;
  border-color: #ff4d4f;
}

.floating-action-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .floating-input-container {
    width: 95%;
    padding: 8px 15px;
  }

  .input-wrapper {
    flex-direction: column;
    align-items: stretch;
  }

  .floating-input-field, .floating-submit-btn {
    width: 100%;
  }

  .floating-actions {
    flex-direction: column;
    align-items: center;
  }

  .floating-action-btn {
    width: 100%;
    text-align: center;
  }
}
</style>
